<?php

namespace app\api\controller;
use app\api\exception\Exception;
use app\api\exception\ParameterException;
use app\api\validate\Login as LoginValidate;
use app\api\model\User as UserModel;
use app\api\service\Token;
use think\facade\Validate;

class User extends Base {

  public function __construct() {
    $this->model = new UserModel();
  }

  public function login() {

    $username = input('post.username');
    $password = input('post.password');

    $data = [
      'username' => $username,
      'password' => $password
    ];

    $validate = new LoginValidate();
    if(!$validate->check($data)) {
      throw new ParameterException($validate->getError());
    }

    $result = $this->model->checkUserExist($username, $password);

    if($result) {
      $userId = $result['id'];
      $token = Token::get($userId);
      cache($token, json_encode($result), config('token.expire_in'));
      return success([
        'token' => $token
      ]);
    } else {
      throw new Exception('登录失败');
    }

  }

  public function logout() {
    $token = input('get.token');
    cache($token, null);
    return success();
  }

  public function info() {

    $token = input('get.token');
    $validate = Validate::rule('token', 'require');
    $result = $validate->check([
      'token' => $token
    ]);

    if(!$result) {
      throw new ParameterException($validate->getError());
    } else {
      $info = json_decode(cache($token));
      $data = [
        'name' => $info->username,
        'avatar' => $info->avatar,
        'roles' => $info->roles
      ];
      return success($data);
    }
  }

  public function create() {
    $data = input('post.');
    $data['password'] = md5($data['password']);
    $data['avatar'] = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif';
    if(!empty($data['id'])) {
      $this->model->update($data);
    } else {
      $this->model->save($data);
    }
    return success();
  }

}